package logic

import (
	"C/Rpc/model/Es"
	"bytes"
	"context"
	"encoding/json"
	"log"

	"C/Rpc/internal/svc"
	"C/Rpc/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsSearLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSearLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSearLogic {
	return &EsSearLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// es搜索
func (l *EsSearLogic) EsSear(in *shop.EsSearRequest) (*shop.GoodListResponse, error) {
	// todo: add your logic here and delete this line
	var buf bytes.Buffer
	var query map[string]interface{}
	if in.FormWord != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodsTitle": in.FormWord,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := Es.Es.Search(
		Es.Es.Search.WithContext(context.Background()),
		Es.Es.Search.WithIndex("goods"),
		Es.Es.Search.WithBody(&buf),
		Es.Es.Search.WithTrackTotalHits(true),
		Es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	r := map[string]interface{}{}
	json.NewDecoder(res.Body).Decode(&r)
	var list []*shop.GoodItem
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		m := hit.(map[string]interface{})["_source"].(map[string]interface{})
		list = append(list, &shop.GoodItem{
			UserId:     int64(m["UserId"].(float64)),
			GoodsTitle: m["GoodsTitle"].(string),
			GoodsStock: int64(m["GoodsStock"].(float64)),
			GoodsImage: m["GoodsImage"].(string),
			GoodsPrice: float32(m["GoodsPrice"].(float64)),
			GoodsLike:  int64(m["GoodsLike"].(float64)),
			Status:     int64(m["Status"].(float64)),
			Id:         int64(m["ID"].(float64)),
		})
	}
	return &shop.GoodListResponse{
		List: list,
	}, nil
}
